package com.onenine.app.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.manager.OssManager;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.onenine.app.R;
import com.onenine.app.adapter.DynamicAdapter;
import com.onenine.app.adapter.MultiImageAdapter;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.fragment.CAttentionFragment;
import com.onenine.app.model.DynamicItem;
import com.onenine.app.request.CommonRequest;
import com.onenine.app.request.DelDynamicRequest;
import com.onenine.app.request.DynamicCoverRequest;
import com.onenine.app.request.DynamicListRequest;
import com.onenine.app.request.EditDynamicRequest;
import com.onenine.app.request.PageRequest;
import com.onenine.app.response.DynamicListResponse;
import com.onenine.app.response.EditCoverResponse;
import com.onenine.app.response.UserInfoResponse;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.GlideUtils;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.TransitionViewHelper;
import com.onenine.app.view.dialog.DynamicCoverDialog;
import com.onenine.app.view.nineimage.NineGridImageView;
import com.onenine.app.view.popwin.DynamicPopWindow;
import com.onenine.base.base.BasePageListActivity;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.utils.StatusBarUtils;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.NiceImageView;
import com.onenine.base.view.PullRefreshRecyclerView;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ActivityUtils;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.SizeUtils;
import com.onenine.dialog.CommonTextDialog;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.jzvd.Jzvd;
import pub.devrel.easypermissions.EasyPermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 动态列表
 */
public class DynamicListActivity extends BasePageListActivity implements View.OnClickListener
        , OssManager.Callback, MultiImageAdapter.OnItemImageClickListener, BaseMultiItemQuickAdapter.OnItemChildClickListener {

    private CollapsingToolbarLayout mCollapsingLayout;
    private NineGridImageView mClickMultiImageView;
    private NiceImageView mAvProfile;
    private TextView mDynamicCount;
    private ImageView mIvBackground;
    private String mUserId;
    private boolean isMySelf;

    public static void launchActivity(Context context, String userId, String coverUrl) {
        Intent intent = new Intent(context, DynamicListActivity.class);
        intent.putExtra("userId", userId);
        intent.putExtra("coverUrl", coverUrl);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_my_dynamic;
    }

    @Override
    protected void initViews() {
        super.initViews();
        StatusBarUtils.setTransparentForImageView(this, mAvProfile);
        mToolbar.setLayoutBackgroundColor(Color.TRANSPARENT);
        mToolbar.setBottomDividerVisible(false);
        mToolbar.setCenterTitle(isMySelf ? R.string.my_dynamic : R.string.user_dynamic);
        mToolbar.setCenterTitleColor(Color.WHITE);
        mToolbar.setLeftDrawable(R.drawable.ic_back_white);
        mDynamicCount = findViewById(R.id.tv_count);
        mAvProfile = findViewById(R.id.av_profile);
        mIvBackground = findViewById(R.id.iv_background);
        mCollapsingLayout = findViewById(R.id.collapsing_toolbar_layout);
        mPullRefreshView.setRefreshBackgroundColor(Color.WHITE);
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mToolbar.setOnRightClickListener(this);
        mIvBackground.setOnClickListener(this);
        mPullRefreshView.setOnChildClickListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

    @Override
    protected Pair<PullRefreshRecyclerView, RecyclerView.Adapter> initPullRefreshView() {
        mUserId = getIntent().getStringExtra("userId");
        isMySelf = TextUtils.equals(mUserId, RcUser.getInstance().getUserId());
        return Pair.create(findViewById(R.id.pull_to_refresh_layout)
                , new DynamicAdapter(isMySelf, this));
    }

    /**
     * 加载用户信息
     */
    private void loadUserInfo() {
        if (isMySelf) {
            mToolbar.setRightTitleDrawable(R.drawable.ic_circle_plus);
            showUserInfo(RcUser.getInstance().getInfoResponse());
        } else {
            OkRequest.getInstance().withUrl(UrlConfig.GET_PERSONAL_INFO)
                    .withRequest(new CommonRequest(mUserId))
                    .doRequest(DynamicListActivity.class.getSimpleName(), new OkCallback<UserInfoResponse>() {
                        @Override
                        public void onResponse(UserInfoResponse response, String srcData) {
                            if (response.isSuccess()) {
                                showUserInfo(response);
                            }
                        }
                    });
        }
    }

    @Override
    protected void loadPageData(int pageNum) {
        PageRequest request;
        if (isMySelf) {
            request = new PageRequest();
        } else {
            request = new DynamicListRequest();
            ((DynamicListRequest) request).setTargetUserId(mUserId);
        }
        request.setUserId(RcUser.getInstance().getUserId());
        request.setPageSize(AppConfig.PAGE_SIZE);
        request.setPageNum(pageNum);
        OkRequest.getInstance().withUrl(isMySelf ? UrlConfig.MY_DYNAMIC : UrlConfig.TA_DYNAMIC)
                .withRequest(request).doRequest(CAttentionFragment.class.getSimpleName(), new OkCallback<DynamicListResponse>() {
            @Override
            public void onResponse(DynamicListResponse response, String srcData) {
                dismissRefreshStatus();
                if (response.isSuccess()) {
                    notifyDataSuccess(response.getDynamicItemList());
                    if (response.getPageInfo() != null) {
                        mDynamicCount.setText(getString(R.string.dynamic_total_format
                                , response.getPageInfo().getTotalRecord()));
                    }
                } else {
                    notifyDataFailure();
                }
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        loadUserInfo();
        loadPageData(1);
        loadCoverBackground();
    }

    /**
     * 加载封面图
     */
    private void loadCoverBackground() {
        String coverUrl = getIntent().getStringExtra("coverUrl");
        if (!TextUtils.isEmpty(coverUrl)) {
            GlideUtils.loadSrcImage(ApUtils.getApp(), mIvBackground, coverUrl);
        } else {
            mIvBackground.setImageResource(R.drawable.no_banner);
        }
    }

    /**
     * 显示头像名称
     *
     * @param userInfo
     */
    private void showUserInfo(UserInfoResponse userInfo) {
        if (userInfo == null) {
            return;
        }
        GlideUtils.loadSrcImage(ApUtils.getApp(), findViewById(R.id.av_profile), userInfo.getPhoto());
        TextView tvName = findViewById(R.id.tv_name);
        tvName.setText(userInfo.getNickName());
        mCollapsingLayout.setContentScrimColor(RoleResLoader
                .getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR, userInfo.getSex()));
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_right_title) {
            ActivityUtils.startActivity(this, DynamicPublishActivity.class);
        } else if (v.getId() == R.id.iv_background) {
            if (isMySelf) {
                new DynamicCoverDialog(this, getString(R.string.update_dynamic_cover))
                        .setOnItemClickListener(new DynamicCoverDialog.OnItemClickListener() {
                            @Override
                            public void onItemClick(Dialog dialog, String message) {
                                checkLaunchAlbum();
                            }
                        }).show();
            }
        }
    }

    @Override
    public void onItemClick(Context context, NineGridImageView multiImageView, ImageView imageView) {
        mClickMultiImageView = multiImageView;
    }

    /**
     * 校验权限并启动相册
     */
    private void checkLaunchAlbum() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            launchAlbum(1);
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.permission_extra_storage_hint)
                    , UploadImageActivity.REQ_OPEN_ALBUM, Manifest.permission.READ_EXTERNAL_STORAGE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 101) {
                compressImages(Matisse.obtainPathResult(data));
            }
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        DynamicItem dynamicItem = (DynamicItem) adapter.getItem(position);
        PostDetailActivity.launchActivity(this
                , dynamicItem.getDynamickPkId(), DataType.POST_DYNAMIC, dynamicItem.getSpanType());
    }

    /**
     * 打开相册
     *
     * @param maxCount
     */
    private void launchAlbum(int maxCount) {
        int size = AppConfig.SCREEN_WIDTH / 3 - SizeUtils.dp2px(10);
        Matisse.from(this)
                .choose(MimeType.ofImage())//只显示照片
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, getPackageName() + ".fileprovider"))
                .countable(false)//无序选择图片
                .showSingleMediaType(true)
                .maxSelectable(maxCount)//最大选择数量
                .gridExpectedSize(size)//图片显示表格的大小getResources()
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//图像选择和预览活动所需的方向。
                .thumbnailScale(0.85f)//缩放比例
                .theme(R.style.Matisse_Light)//主题
                .imageEngine(new GlideEngine())//加载方式
                .forResult(101);//请求码
    }

    /**
     * 压缩图片在100kb左右
     *
     * @param images
     */
    private void compressImages(List<String> images) {
        Luban.with(this)
                .load(images).ignoreBy(100)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(final File file) {
                        OssManager.getInstance(ApUtils.getApp()).ossUpload(new ArrayList<String>() {{
                            add(file.getAbsolutePath());
                        }}, new ArrayList<String>(), DynamicListActivity.this);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }

    @Override
    public void onSuccess(final String url) {
        OkRequest.getInstance().withUrl(UrlConfig.UPDATE_DYNAMIC_BACKGROUND)
                .withRequest(new DynamicCoverRequest(mUserId, url))
                .doRequest(DynamicListActivity.class.getSimpleName(), new OkCallback<EditCoverResponse>() {
                    @Override
                    public void onResponse(EditCoverResponse response, String srcData) {
                        if (response.isSuccess()) {
                            Toasty.showNormal(R.string.setting_success);
                            GlideUtils.loadSrcImage(ApUtils.getApp(), mIvBackground, response.getBackgroundPicture());
                            UserInfoResponse pr = RcUser.getInstance().getInfoResponse();
                            if (pr != null) {
                                pr.setBackgroundPicture(response.getBackgroundPicture());
                            }
                        }
                    }
                });
    }

    @Override
    public void onProgress(float progress) {

    }

    @Override
    public void onFailure(int errorCode, String errorMsg) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshEvent event) {
        if (event.type == DataType.REFRESH_DYNAMIC_PUBLISH_SUCCESS) {
            onRefresh();
        }
    }

    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            int position = data.getIntExtra(BrowserImageActivity.IMG_CURRENT_POSITION, -1);
            if (position >= 0) {
                //多图查看返回
                if (mClickMultiImageView != null) {
                    TransitionViewHelper.onActivityReenter(this
                            , mClickMultiImageView.getImageView(position));
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        if (view.getId() == R.id.btn_permission) {
            DynamicItem item = (DynamicItem) adapter.getItem(position);
            new DynamicPopWindow(this, new DynamicPopWindow.OnItemClickListener() {
                @Override
                public void onItemClick(int permission, String permissionDesc) {
                    if (permission == DynamicPopWindow.DYNAMIC_DELETE) {
                        //删除动态
                        showDeleteConfirmDialog(item.getDynamickPkId(), position);
                    } else {
                        //编辑权限
                        execEditOperation(item, permission, position);
                    }
                }
            }).showPopWindow();
        }
    }

    /**
     * 删除动态前二次确认
     */
    private void showDeleteConfirmDialog(String pkId, int position) {
        new CommonTextDialog.Builder(this)
                .setText(R.string.delete_dynamic_confirm_hint)
                .setOnOkClickListener(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        execDelOperation(pkId, position);
                    }
                }).builder().show();
    }

    /**
     * 执行删除
     *
     * @param pkId
     */
    private void execDelOperation(String pkId, int position) {
        DelDynamicRequest request = new DelDynamicRequest();
        request.setPkId(pkId);
        request.setUserId(RcUser.getInstance().getUserId());
        OkRequest.getInstance().withUrl(UrlConfig.DELETE_DYNAMIC)
                .withRequest(request).doRequest(DynamicListActivity.class.getSimpleName(), new OkCallback<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response, String srcData) {
                if (response.isSuccess()) {
                    //删除成功，界面移除
                    mPullRefreshView.removeData(position);
                } else {
                    Toasty.showNormal(response.getMessage());
                }
            }
        });
    }

    /**
     * 编辑动态权限
     *
     * @param item
     * @param permission
     * @param position
     */
    private void execEditOperation(DynamicItem item, int permission, int position) {
        EditDynamicRequest request = new EditDynamicRequest();
        request.setPkId(item.getDynamickPkId());
        request.setUserId(RcUser.getInstance().getUserId());
        request.setDynPower(permission);
        OkRequest.getInstance().withUrl(UrlConfig.EDIT_DYNAMIC_PERMISSION)
                .withRequest(request).doRequest(DynamicListActivity.class.getSimpleName(), new OkCallback<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response, String srcData) {
                if (response.isSuccess()) {
                    //编辑成功，界面刷新
                    Toasty.showNormal(R.string.operate_success);
                    item.setDynPower(permission);
                    mAdapter.notifyItemChanged(position);
                    mPullRefreshView.updateData(position, item);
                } else {
                    Toasty.showNormal(response.getMessage());
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}